package com.supermali.util;

import java.awt.*;
import java.awt.geom.Point2D;

public class IntersectionUtil {

    public static boolean rectrectIntersection(Rectangle rectangle1,Rectangle rectangle2){
        // 计算点的坐标
        double x1 = rectangle1.getX();
        double y1 = rectangle1.getY();
        double width1 = rectangle1.getWidth();
        double height1 = rectangle1.getHeight();
        double maxX1 = x1+width1;
        double minY1 = y1;
        double minX1 = x1;
        double maxY1 = y1+height1;
        Point2D A0 = new Point2D.Double(minX1,maxY1);
        Point2D A1 = new Point2D.Double(maxX1,maxY1);
        Point2D A2 = new Point2D.Double(maxX1,minY1);
        Point2D A3 = new Point2D.Double(minX1,minY1);
        // 计算第二个矩形坐标
        double x2 = rectangle2.getX();
        double y2 = rectangle2.getY();
        double width2 = rectangle2.getWidth();
        double height2 = rectangle2.getHeight();
        double maxX2 = x2+width2;
        double minY2 = y2;
        double minX2 = x2;
        double maxY2 = y2+height2;
        Point2D B0 = new Point2D.Double(minX2,maxY2);
        Point2D B1 = new Point2D.Double(maxX2,maxY2);
        Point2D B2 = new Point2D.Double(maxX2,minY2);
        Point2D B3 = new Point2D.Double(minX2,minY2);
        // 开始计算
        Vector2f N0 = Vector2f.getVector2f(A1, A0).div(2.0d);
        Vector2f N1 = Vector2f.getVector2f(A2, A1).div(2.0d);
        Point2D.Double CA1 = new Point2D.Double((A0.getX() + A2.getX()) / 2, (A0.getY() + A2.getY()) / 2);
        Vector2f CA = Vector2f.getVector2f(new Point2D.Double(0,0),CA1);
        double D0 = N0.len();
        double D1 = N1.len();
        N1=N1.div(D1);
        N0=N0.div(D0);

        Vector2f N2 = Vector2f.getVector2f(B1, B0).div(2.0d);
        Vector2f N3 = Vector2f.getVector2f(B2, B1).div(2.0d);
        Point2D.Double CB1 = new Point2D.Double((B0.getX() + B2.getX()) / 2, (B0.getY() + B2.getY()) / 2);
        Vector2f CB = Vector2f.getVector2f(new Point2D.Double(0,0),CB1);
        double D2 = N2.len();
        double D3 = N3.len();
        N2=N2.div(D2);
        N3=N3.div(D3);

        Vector2f C = CA.sub(CB);
        double DA= D0;
        double DB=D2*Math.abs(N2.dot(N0));
        DB+=D3*Math.abs(N3.dot(N0));
        if(DA+DB<Math.abs(C.dot(N0))) return false;
        DA=D1;
        DB=D2*Math.abs(N2.dot(N1));
        DB+=D3*Math.abs(N3.dot(N1));
        if(DA+DB<Math.abs(C.dot(N1))) return false;
        DA=D2;
        DB=D0*Math.abs(N0.dot(N2));
        DB+=D1*Math.abs(N1.dot(N2));
        if(DA+DB<Math.abs(C.dot(N2))) return false;

        DA=D3;
        DB=D0*Math.abs(N0.dot(N3));
        DB+=D1*Math.abs(N1.dot(N3));
        if(DA+DB<Math.abs(C.dot(N3))) return false;
        return true;
    }

}
